package com.elevator;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JPanel;

enum doorUIStatus
{
	doorUIOpening,
	doorUIOpened,
	doorUIClosing,
	doorUIClosed,
        doorUIReset,
}
interface doorUIEventListener
{
	public void doorUIEvent(doorUIStatus nStatus);
}
public class doorUI extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Timer mTimer = new Timer();
	public doorUIEventListener mListener=null;
	private int mDoorWidth = 0;
	private int mDoorMaxWidth = 0;
	private int mPersionNum = 0;
	//-2 opening -1 opened 0 closing 1 closed
	private doorUIStatus mDoorStatus = doorUIStatus.doorUIClosed;
	public doorUI()
	{
		this(60, 100);
	}
	public doorUI(int w,int h) {
		this.setSize(w, h);
		mDoorMaxWidth = this.getSize().width/2 - 1;
		mDoorWidth = mDoorMaxWidth;
	}
	public void setPersonNum(int num)
	{
		mPersionNum = num;
	}
	public void startOpenDoor() {
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mDoorWidth <=0) {
					mTimer.cancel();
					mDoorStatus = doorUIStatus.doorUIOpened;
					if (mListener != null)
					{
						mListener.doorUIEvent(mDoorStatus);
					}
					doorUI.this.startCloseDoor();
				}
				else {
					mDoorWidth--;
					mDoorStatus = doorUIStatus.doorUIOpening;
				}
				doorUI.this.repaint();
			}
		}, 300, 50);
	}
	public void startCloseDoor(){
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mDoorWidth >=mDoorMaxWidth) {
					mTimer.cancel();
					mDoorStatus=doorUIStatus.doorUIClosed;
					if (mListener != null)
					{
						mListener.doorUIEvent(mDoorStatus);
					}
				}
				else {
					mDoorWidth++;
					mDoorStatus=doorUIStatus.doorUIClosing;
				}
				doorUI.this.repaint();
			}
		}, 1000, 50);
	}
	public doorUIStatus getDoorUIStatus()
	{
		return mDoorStatus;
	}
	@Override
	public void paint(Graphics g) {
		//super.paint(g);
		Dimension size = this.getSize();
		
		g.setColor(Color.darkGray);
		g.fillRect(0, 0, size.width, size.height);
		if (mDoorStatus == doorUIStatus.doorUIOpening
			|| mDoorStatus == doorUIStatus.doorUIOpened
			|| mDoorStatus == doorUIStatus.doorUIClosing) {
			for (int i = 0; i < mPersionNum; i++) {
				g.setColor(Color.blue);
				g.drawRoundRect(5+3*i, size.height - 50+5, 15, 15, 15, 15);
				g.drawLine(13+3*i,size.height- 50+20, 30+3*i,size.height- 50+35);
				g.drawLine(13+3*i,size.height- 50+20, 0+3*i,size.height- 50+35);
				g.drawLine(8+3*i,size.height- 50+29, 8+3*i,size.height- 50+50);
				g.drawLine(18+3*i,size.height- 50+29, 18+3*i,size.height- 50+50);
			}

		}
		g.setColor(Color.orange);
		g.fillRect(0, 0, mDoorWidth, size.height);
		g.fillRect(size.width - mDoorWidth, 0, mDoorWidth, size.height);
	}
}
